package com.xiong.springcloud.controller;

import com.xiong.springcloud.entities.Payment;
import com.xiong.springcloud.result.CodeMsg;
import com.xiong.springcloud.result.Result;
import com.xiong.springcloud.service.impl.PaymentServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wardseptember
 * @create 2020-03-27 17:01
 */
@RestController
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentServiceImpl paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment/create")
    public Result<Payment> create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("插入结果"+result);
        if (result > 0) {
            log.info("serverPort: "+serverPort);
            return Result.success(payment);
        } else {
            return Result.error(CodeMsg.INSERT_FAILED);
        }

    }

    @GetMapping("/payment/get/{id}")
    public Result<Payment> getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        log.info("查询结果"+payment);
        if (payment != null) {
            log.info("serverPort: "+serverPort);
            return new Result<>(200, serverPort, payment);
//            return Result.success(payment);
        } else {
            return Result.error(CodeMsg.SELECT_FAILED);
        }
    }

    @GetMapping("/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("service: "+ service);
        }
        List<ServiceInstance > instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getInstanceId()+"\t"+instance.getServiceId()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping("/payment/lb")
    public String getPaymentLB() {
        return serverPort;
    }

    @GetMapping("/payment/zipkin")
    public String getPaymentZipkin() {
        return serverPort+"hello ZipKin";
    }

    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeout() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "8001";
    }
}
